/*
    RecipeViewer: An application for viewing recipes
    Copyright (C) 2009  Wade Smith

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "viewerwindow.h"

#include <QtGui/QMenu>
#include <QtGui/QApplication>
#include <QtGui/QStyle>
#include <QtGui/QMenuBar>
#include <QtGui/QTextEdit>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QSettings>
#include <QtXmlPatterns/QXmlQuery>
#include <QtGui/QFileDialog>
#include <QtCore/QDir>
#include <QtGui/QMessageBox>
#include <QtGui/QCloseEvent>

ViewerWindow::ViewerWindow()
{
    this->buildInterface();
}

ViewerWindow::ViewerWindow(char *fileName)
{
    this->buildInterface();
    this->loadFile(QString(fileName));
}

// Create the GUI
void ViewerWindow::buildInterface()
{
    this->setWindowTitle(qApp->applicationName());

    // Menus
    recipeMenu = new QMenu("&Recipe");
    recipeMenu->addAction(qApp->style()->standardIcon(QStyle::SP_DialogOpenButton), "&Open...", this,
                          SLOT(openSlot()));
    recipeMenu->addAction(qApp->style()->standardIcon(QStyle::SP_DialogSaveButton), "&Save Copy...", this,
                          SLOT(saveCopySlot()));
    recipeMenu->addSeparator();
    recipeMenu->addAction(qApp->style()->standardIcon(QStyle::SP_DialogCloseButton), "&Close", this,
                          SLOT(close()));
    this->menuBar()->addMenu(recipeMenu);

    helpMenu = new QMenu("&Help");
    helpMenu->addAction("&About", this, SLOT(aboutSlot()));
    this->menuBar()->addMenu(helpMenu);

    // Central display widget
    centreWidget = new QTextEdit;
    centreWidget->setReadOnly(true);
    this->setCentralWidget(centreWidget);

    // Style sheet
    QFile *styleSheet = new QFile("./style.css");
    if (!styleSheet->open(QFile::ReadOnly | QFile::Text))
    {
        centreWidget->setHtml("<html><body><h1>Warning</h1><p>Unable to open style sheet file "
                              + styleSheet->fileName() + "</p></body></html");
    }
    else
    {
        QTextStream *stream = new QTextStream(styleSheet);
        centreWidget->document()->setDefaultStyleSheet(stream->readAll());
    }

    // Set up and load application settings
    settings = new QSettings;

    this->resize(settings->value("Window/Size").toSize());
    this->move(settings->value("Window/Position").toPoint());
}

// Load a recipe file, create a HTML equivalent, and display it
void ViewerWindow::loadFile(QString fileName)
{
    QFile *file = new QFile(fileName);

    if (!file->open(QFile::ReadOnly | QFile::Text))
    {
        centreWidget->setHtml("<html><body><h1>Error</h1><p>Unable to open file "
                              + file->fileName() + "</p></body></html>");
        return;
    }

    QXmlQuery *xQuery = new QXmlQuery;
    xQuery->bindVariable("file", file);
    xQuery->setQuery(QUrl("./rcp2htm.xq"));
    QString *output = new QString;
    xQuery->evaluateTo(output);

    centreWidget->setHtml(*output);

    file->close();
    currentFileName = fileName;
}

void ViewerWindow::openSlot()
{
    QString fileName = QFileDialog::getOpenFileName(this, "Open", QDir::homePath(), "Recipes (*.rcp)");
    if (!fileName.isEmpty())
    {
        loadFile(fileName);
    }
}

void ViewerWindow::saveCopySlot()
{
    if (!currentFileName.isEmpty())
    {
        QString saveFileName = QFileDialog::getSaveFileName(this, "Save Copy", QDir::homePath()
                                                            + "/Untitled.rcp", "Recipes (*.rcp)");
        if (!saveFileName.isEmpty())
        {
            if (!QFile::copy(currentFileName, saveFileName))
            {
                QMessageBox::warning(this, "Error", "Couldn't save the file");
            }
        }
    }
    else
    {
        QMessageBox::warning(this, "Save Copy", "No file currently open to save a copy of");
    }
}

void ViewerWindow::aboutSlot()
{
    QMessageBox::about(this, "About " + qApp->applicationName(), "<html><body><h1>" + qApp->applicationName()
                       + "</h1><p>An application for viewing recipes.</p><p>Version "
                       + qApp->applicationVersion() + "<br />&nbsp;&nbsp;&nbsp;" + qApp->organizationName()
                       + "</p></body></html>");
}

void ViewerWindow::closeEvent(QCloseEvent *event)
{
    settings->setValue("Window/Size", QVariant(this->size()));
    settings->setValue("Window/Position", QVariant(this->pos()));
    event->accept();
}
